package logic

import (
	"context"
	"fmt"
	"time"
	"zhifubao/model/cache"
	"zhifubao/model/mysql"

	"zhifubao/zhifubaorpc/internal/svc"
	"zhifubao/zhifubaorpc/zhifubaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zhifubaorpc.LoginRequest) (*zhifubaorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var finduser mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("该用户不存在 请去注册")
	}
	if finduser.Password == "" {
		return nil, fmt.Errorf("密码不能为空")

	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != in.SendCode {
		return nil, fmt.Errorf("验证码不匹配,请重新输入")
	}
	cache.Rdb.Set(l.ctx, "SendSms"+in.Account, result, time.Minute*3)

	captcha, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Account).Result()
	if captcha != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证不匹配,请重新输入")
	}
	cache.Rdb.Set(l.ctx, "SendSms"+in.Account, result, time.Minute*3)

	if finduser.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}

	return &zhifubaorpc.LoginResponse{
		Id: int64(finduser.ID),
	}, nil
}
